package com.huahai.security.core.authentication.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: Jun
 * @Date: 2020/7/19
 *
 * 解决认证过的用户访问无权限资源时的异常,即授权异常
 */
public class CustomAccessDeniedHandler  implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        ObjectMapper objectMapper = new ObjectMapper();
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpStatus.SC_FORBIDDEN);
        PrintWriter printWriter = response.getWriter();
        Map<String, String> map = new HashMap<>(2);
        map.put("status", "403");
        map.put("message", "当前用户无权限访问，请联系管理员");
        String resBody = objectMapper.writeValueAsString(map);
        printWriter.print(resBody);
        printWriter.flush();
        printWriter.close();
    }
}
